#define _CRT_SECURE_NO_WARNINGS 1
#include"list.h"
ListNode* BuyNode(LTDateType x)
{
	ListNode* NewNode = malloc(sizeof(ListNode));
	if (NewNode == NULL)
	{
		perror("Malloc Fail!");
		exit(1);
	}
	NewNode->data = x;
	NewNode->next = NewNode->prev = NewNode;
	return NewNode;
}

//void LTInitialise(ListNode** pphead)
//{
	//创建一个头结点（哨兵卫）
	//*pphead = BuyNode(-1);
//}
ListNode* LTInitialise(ListNode*phead)
{
	phead=BuyNode(-1);
  return phead;
}
void LTDestroy(ListNode** pphead)
{
	assert(*pphead && pphead);
	ListNode*pcur = (*pphead)->next;
	while (pcur!=*pphead)
	{
		ListNode* Next = pcur->next;
		free(pcur);
		pcur = Next;
	}
	free(*pphead);
	*pphead = NULL;
	pcur = NULL;
}
//void LTDestroy(ListNode* phead)
//{
//	assert(phead);
//	ListNode* pcur = phead->next;
//	while (pcur != phead)
//	{
//		ListNode* Next = pcur->next;
//		free(pcur);
//		pcur = Next;
//	}
//	free(phead);
//	phead = NULL;
//	pcur = NULL;//实参手动置为空或者重新封装一个函数
//}
void LTPushBack(ListNode* phead, LTDateType x)
{
	assert(phead);
	ListNode* NewNode = BuyNode(x);
	NewNode->next = phead;
	NewNode->prev = phead->prev;
	phead->prev->next = NewNode;
	phead->prev = NewNode;
}

void LTPushFront(ListNode* phead, LTDateType x)
{
	assert(phead);
	ListNode* NewNode = BuyNode(x);
	NewNode->prev = phead;
	NewNode->next = phead->next;
	phead->next->prev = NewNode;
	phead->next = NewNode;
}

//打印双向链表
void LTPrint(ListNode* phead)
{
	ListNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}

bool LTEmpty(ListNode* phead)
{
	if (phead->next == phead)
		return false;
	else
		return true;
}

void LTPopBack(ListNode* phead)
{
	assert(phead);
	assert(LTEmpty(phead));
	ListNode* del = phead->prev;
	ListNode* prev = del->prev;
	prev->next = phead;
	phead->prev = prev;
	free(del);
	del = NULL;
}

void LTPopFront(ListNode* phead)
{
	assert(phead);
	assert(LTEmpty(phead));
	ListNode* del = phead->next;
	ListNode* Next = del->next;
	Next->prev = phead;
	phead->next = Next;
	free(del);
	del = NULL;
}

ListNode* LTFind(ListNode* phead, LTDateType x)
{
	ListNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void LTInsert(ListNode* pos,LTDateType x)
{
	assert(pos);
	ListNode* NewNode = BuyNode(x);
	NewNode->next = pos->next;
	NewNode->prev = pos;
	pos->next->prev = NewNode;
	pos->next = NewNode;
}
void LTErase(ListNode* pos)
{
	assert(pos);
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;

	free(pos);
	pos = NULL;
}